var CTX_CARD = _ctx + '/cfgmgr/card/';
var CTX_NE_URL = _ctx + '/cfg/ne/';
var CTX_CARD_URL = _ctx + '/cfg/card/';
var CTX_CFG = _ctx + '/sys/config/';
var addCardMenuData;
var CATALOG = 'mgr_card';
//全局网元id
var nid = 0;
//业务槽位编号
var slotList = {1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8};
//系统槽位编号
var SLOT_PWR_1 = 6;
var SLOT_PWR_2 = 7;
var SLOT_FAN = 8;

var TYPE_PWR_1 = 6;
var TYPE_PWR_2 = 6;
var TYPE_FAN = 7;

var sysSlotList = [{slot:SLOT_PWR_1,type:TYPE_PWR_1}, 
                   		   {slot:SLOT_PWR_2,type:TYPE_PWR_2}, 
                   		   {slot:SLOT_FAN,type:TYPE_FAN} ];

$(document).ready(function() {
	parent.commonAPI.showProgress();
	updateListener();
	initSortOrder();
	initCardType();
	initCards();
	initSysCards();
	checkCardStatus();	
});

/**
 * 检测板卡状态
 */
function checkCardStatus(){
	$.get(CTX_NE_URL + 'queryNeCards/' + nid, function(result){		
		$(result).each(function(index,data){
			//var slot = $("[slot="+data.slot+"]");
 			slotList[data.slot] = null;			
		});
		
		//设置槽位信息
		parent.commonAPI.setNeTable(nid, slotList);
		
		/**
		 * 将空槽位标红
		 */
		for(var ii = 1; ii < 9; ii ++) {
			var slot = slotList[ii];
			if(slot != null || slot != undefined) {
				var slotItem = $("[slot="+slot+"]");
				//slotItem.css('border-color','red');
				//slotItem.css('border-width','2px');
				//解除绑定事件
				slotItem.unbind('dblclick');
				slotItem.bind('dblclick',function(){
					parent.commonAPI.warn('错误','板卡未插入，请检测物理板卡是否插入槽位！');
				});
				
				//修改列表情况
				$("[ustatus="+slot+"]").removeClass('label-green').addClass('label-red');
				$("[ustatus="+slot+"]").html('异常&nbsp;');
			}
		}
		parent.commonAPI.hideProgress();
	});
}

/**
 * 读取板卡类型
 */
function initCardType(){
	var url = CTX_CARD_URL + 'listCardType';
	var ajaxSetting = {url:url, success:function(result){
		addCardMenuData = [[{text:"插入",data:[]}]];
		var dataList = new Array();
		$(result).each(function(index,data){
			dataList.push({
					text : data.label,
					func : function() {
						insertCard($(this), data.value, data.label);
					}
				});
			
		});
		
		addCardMenuData[0][0].data = [dataList];		
		updateListener();
	}};
	parent.commonAPI.ajaxProgress('读取网元板卡信息，等待设备响应....', ajaxSetting);
}

/**
 * 初始化业务板卡(1~4号槽位)
 */
function initCards(){
	var nidStr = GetQueryString('nid');
	nid = nidStr.substr(nidStr.indexOf("_")+1);
	var url = CTX_NE_URL + 'listCard/' + nid;
	var ajaxSetting = {url:url, 
			success:function(result){		
				$(result).each(function(index,data){
					updateCard(data);
				});
				updateListener();
			}};
	parent.commonAPI.ajaxProgress('读取网元板卡信息，等待设备响应....', ajaxSetting);
}

/**
 * 根据板卡类型获取系统板卡
 * @param type
 * @param list
 */
function getSysCardByType(type, list){
	var out = null;
	$(list).each(function(index, data){
		if(parseInt(data.card.type) == type){
			out = data;
			return;
		}
	});
	return out;
}

/**
 * 初始化系统板卡(5~8号槽位)
 */
function initSysCards(){
	var url = CTX_CARD_URL + 'getAllCardConfig/';
	var ajaxSetting = {url:url, 
			success:function(result){		
				$(sysSlotList).each(function(index, data){
					var slot = getSysCardByType(data.type, result);
					if(slot!=null) {
						slot.num = data.slot;
						slot.slotid = data.slot;						
						updateCard(slot);
					}
				});
				updateListener();
			}};
	parent.commonAPI.ajaxProgress('读取网元板卡信息，等待设备响应....', ajaxSetting);
}

/**
 * 更新指定槽位板卡内容
 * @param slot
 * @param content
 */
function updateCard(result) {
	var cardBlock = $("[slot="+result.num+"]"); 
	if(result.card !=null ){
		cardBlock.html('<br>'+result.num+":"+result.card.cardname);
		cardBlock.attr('cid', result.card.cardid);
		cardBlock.attr('class', 'card');
		cardBlock.attr('sid', result.slotid);
		removeCardListener(cardBlock);
	}
}

function initSortOrder(){
	$("#list1, #list2, #list3, #list4").dragsort({ dragSelector: "div", 
		dragBetween: false, 
		dragEnd: saveOrder, 
		placeHolderTemplate: "<li class='placeHolder'><div></div></li>" 
	});
	
}

/**
 * 保存槽位顺序
 */
function saveOrder() {
	var data = $("#list2 li").map(function() { return $(this).children().attr('slot'); }).get();
	swapCard(data);
	$("input[name=vSortOrder]").val(data.join("|"));
	//parent.commonAPI.info('通知', '更新板卡槽位成功！' + data);
};

/**
 * 菜单数据
 */
//初始化菜单
var removeCardMenuData = [ [ {
	text : "拔除板卡",
	func : function() {
		removeCard($(this));		
	}
} ] ];

/**
 * 更新侦听器
 */
function updateListener(){
	$('.card').dblclick(function(){		
		var cid = $(this).attr('cid');
		//正则替换所有的<br>		
		var regx = new RegExp("<br>","gi");
		var title = $(this).html().replace(regx,'');
		var url = '/webbase/core/index/cardConfig/' + cid;
		parent.commonAPI.createTab(cid, title, url);
	});
	
	$(".card").smartMenu(removeCardMenuData, {
		name : "card"
	});
	$(".empty").smartMenu(addCardMenuData, {
		name : "empty"
	});
}

/**
 * 给对象增加添加板卡事件
 */
function addCardListener(item){
	item.smartMenu(addCardMenuData, {name : "empty"});	
	item.dblclick(function(){		
		var id = $(this).attr('slot');
		//正则替换所有的<br>		
		var regx = new RegExp("<br>","gi");
		var title = $(this).html().replace(regx,'');
		var url = '/webbase/core/index/cardConfig';
		parent.commonAPI.createTab(id, title, url);
	});
}

/**
 * 给对象增加删除板卡事件
 */
function removeCardListener(item){
	item.smartMenu(removeCardMenuData, {name : "card"});
}

/**
 * 移动板卡
 */
function swapCard(dragEndData){
	//alert('before : ' + $("input[name=vSortOrder]").val() + ' after: ' + dragEndData);
}

function GetQueryString(name)
{
     var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
     var r = window.location.search.substr(1).match(reg);
     if(r!=null)return  unescape(r[2]); return null;
}

/**
 * 插入板卡
 * insertCard/{type},{chassis},{slot}
 * @param name
 */
function insertCard(target, type, lblName){		
	//parent.commonAPI.hideProgress();
	//parent.commonAPI.showProgress();
	var sid = target.attr('slot');
	var ajaxSetting = {url: CTX_CARD_URL + 'addCard/' + nid + '/' + sid + '/' + type, 
			type : "GET",			
			success:function(result){
				if(result.result == '0') {			
					parent.commonAPI.warn('错误',  result.message);			
					parent.commonAPI.blink(target, 'empty', 'label-red card');			
				} else {
					target.attr('class','card');
					target.attr('ctype', type);
					target.html('<br>'+ sid + ':' + lblName);	
					parent.commonAPI.info('信息', result.message);
					//注册删除板卡侦听器	
					removeCardListener(target);
					//parent.commonAPI.hideProgress();
					//获取最后一次选择的节点
					var lstItem = parent.commonAPI.getLstItem();
					//刷新页面					
					//parent.commonAPI.refreshAll(true);
					/*parent.commonAPI.initTree(true);*/
					parent.commonAPI.updateAvailbleSlot(lstItem);
				}				
				//parent.commonAPI.hideProgress();
				refresh();
	}};
	parent.commonAPI.ajaxProgress('插入板卡中，等待设备响应....', ajaxSetting);
	
}

/**
 * 拔除板卡
 * delCard/{type},{chassis},{slot}
 */
function removeCard(target){	
	var sid = target.attr('slot');
	var ajaxSetting = {
		url : CTX_CARD_URL + 'delCard/' + nid + '/' + sid,
		success : function(result) {  
			if(result.result == 1) {
				target.html('<br>' + 'SLOT' + sid);
				target.attr('class', 'empty');
				parent.commonAPI.info('信息', '删除板卡成功。');
				addCardListener(target);
				//获取最后一次选择的节点
				var lstItem = parent.commonAPI.getLstItem();								
				//parent.commonAPI.initTree(true);
				parent.commonAPI.updateAvailbleSlot(lstItem);
				//parent.commonAPI.refreshAll(true);
			} else {
				parent.commonAPI.warn('错误','操作失败，原因：'  + result.message);
			}
			refresh();
			$('#modalProgress').modal('hide');
		}
	};
	
	parent.commonAPI.ajaxProgress('删除板卡中，等待设备响应....', ajaxSetting);
}
